import { getLoginUserUsingGet, userLogoutUsingPost } from '@/request/api/userController'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { message } from 'ant-design-vue'

export const useLoginUserStore = defineStore('loginUser', () => {
  const loginUser = ref<API.UserLoginVO>({})

  /**
   * 登录
   */
  const featureLoginUserGet = async () => {
    let { data: res } = await getLoginUserUsingGet()
    if (res.code === 0 && res.data) {
      loginUser.value = res.data
    } else {
      // 登录过期，删除持久化的登录数据
      localStorage.removeItem('loginUser')
    }
  }
  /**
   * 登出
   */
  const featureUserLogout = async () => {
    let { data: res } = await userLogoutUsingPost()
    if (res.code === 0 && res.data) {
      loginUser.value = {}
      // 清空持久化的登录数据
      localStorage.removeItem('loginUser')
      message.success('登出成功')
    }
  }
  function setLoginUser(newLoginUser: any) {
    loginUser.value = newLoginUser
  }

  return { loginUser, featureLoginUserGet, featureUserLogout,setLoginUser }
}, {
  // 开启持久化，默认对ref对象持久化
  persist: true
})
